package com.mmy.study.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.mmy.study.common.Result;
import com.mmy.study.dao.User;
import com.mmy.study.service.UserService;
import com.mmy.study.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody User userDto) {
        // 获取用户的信息
        String username = userDto.getUsername();
        String password = userDto.getPassword();
        //校验username,password是否为空
        if(StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.fail("error","参数不可以为空!");
        }
        // 找到了这个用户
        User user = userService.loadUserByUsername(username);
        //  继续查询密码是否为正确
        if(user != null && user.getPassword().equals(MD5.create().digestHex(userDto.getPassword()))) {
            // 验证token 是否正确
            String token = TokenUtils.genToken(user.getId().toString(),user.getPassword());
            // 登录成功后 给他分配一个token
            log.info("token"+ token);
            return Result.succ(user, "登录成功");
        }else {
            return Result.succ("fail", "用户名称或者密码不正确");
        }

    }

    @PostMapping("/reg")
    public Result reg(@RequestBody User user) {
        int result = userService.reg(user);
        if (result == 0) {
            //成功
            return Result.succ("success", "注册成功!");
        } else if (result == 1) {
            return Result.fail("error", "用户名重复，注册失败!");
        } else {
            //失败
            return Result.fail("error", "注册失败!");
        }
    }

}
